import 'package:state_beacon/state_beacon.dart';
import '../models/post_model.dart';
import '../models/comment_model.dart';
import 'user_state.dart';

/// 动态状态管理
class PostState {
  // 静态状态变量
  static List<PostModel> _postList = [];
  static List<CommentModel> _commentList = [];
  static Map<String, List<String>> _userFavoritePostsMap = {};

  // State Beacon 实例
  static final postListBeacon = Beacon.writable<List<PostModel>>(_postList);
  static final commentListBeacon = Beacon.writable<List<CommentModel>>(
    _commentList,
  );
  static final userFavoritePostsMapBeacon =
      Beacon.writable<Map<String, List<String>>>(_userFavoritePostsMap);

  /// 初始化默认数据
  static void _initializeDefaultData() {
    if (_postList.isNotEmpty) return; // 避免重复初始化

    // 初始化默认动态数据
    _postList = [
      PostModel(
        postId: 'post_001',
        userId: 'user_001',
        content:
            'On the way to explore Madagascar! The winding roads and the anticipation in flight—can’t wait to dive into this land of wonders, from unique wildlife to breathtaking landscapes. Let the adventure begin! 🚗✈️',
        mediaUrls: ['assets/images/p1.png', 'assets/images/p2.png'],
        videoThumbnails: [
          '', // 第一张是图片
          '', // 第二张是图片
        ],
        publishTime: DateTime.now().subtract(const Duration(hours: 2)),
        favoriteCount: 45,
        commentCount: 8,
        favoritedUserIds: ['user_002', 'user_003'],
      ),
      PostModel(
        postId: 'post_002',
        userId: 'user_002',
        content:
            'Baobab trees in Madagascar—these giants are like living legends! Standing tall under the sky, they’re not just trees but symbols of this magical land. Every angle shows a different kind of grandeur. So in awe of nature’s artistry here. 🤩',
        mediaUrls: [
          'assets/images/p3.png',
          'assets/images/p4.png',
          'assets/images/p5.png',
        ],
        videoThumbnails: [
          '', // 第一张是图片，不需要封面
          '', // 第二个是视频，需要封面
          '',
        ],
        publishTime: DateTime.now().subtract(const Duration(hours: 5)),
        favoriteCount: 32,
        commentCount: 5,
        favoritedUserIds: ['user_001', 'user_004'],
      ),
      PostModel(
        postId: 'post_003',
        userId: 'user_003',
        content:
            'Madagascar is such a wonderland! From the iconic baobab-lined roads to the adorable little creatures, every moment here feels like a dream. So grateful to experience this unique blend of nature and local life. 🥰',
        mediaUrls: [
          'assets/images/p6.png',
          'assets/images/p7.png',
          'assets/images/p8.png',
        ],
        videoThumbnails: [
          '', // 第一张是图片
          '', // 第二张是图片
          '', // 第三张是图片
        ],
        publishTime: DateTime.now().subtract(const Duration(hours: 8)),
        favoriteCount: 67,
        commentCount: 12,
        favoritedUserIds: ['user_001', 'user_002', 'user_005'],
      ),
      PostModel(
        postId: 'post_004',
        userId: 'user_004',
        content:
            'Found a beautiful radiated tortoise in the spiny forest today. These ancient creatures can live over 100 years! Unfortunately, they\'re critically endangered due to habitat loss and illegal trade. Conservation efforts are crucial for their survival. 🐢💚',
        mediaUrls: ['assets/images/p9.png'],
        videoThumbnails: [''],
        publishTime: DateTime.now().subtract(const Duration(days: 1)),
        favoriteCount: 28,
        commentCount: 6,
        favoritedUserIds: ['user_002', 'user_006'],
      ),
      PostModel(
        postId: 'post_005',
        userId: 'user_005',
        content:
            'Feeding these cute monkeys in Madagascar is such a heartwarming experience! Being so close to wildlife in this amazing land makes me feel deeply connected to nature. Every moment here is precious. 🐒💚',
        mediaUrls: ['assets/images/p10.png', 'assets/images/p11.png'],
        videoThumbnails: [
          '', // 第一张是图片
          '', // 第二张是图片
        ],
        publishTime: DateTime.now().subtract(const Duration(days: 1, hours: 3)),
        favoriteCount: 89,
        commentCount: 15,
        favoritedUserIds: ['user_001', 'user_003', 'user_007'],
      ),
      PostModel(
        postId: 'post_006',
        userId: 'user_006',
        content:
            'Just look at these adorable lemurs in Madagascar! They’re so lively and unique, truly the stars of this magical island. Every time I see them, I’m amazed by how special nature is here. 🦎💖',
        mediaUrls: ['assets/images/p12.png', 'assets/images/p13.png'],
        videoThumbnails: [''], // 只有一张图片
        publishTime: DateTime.now().subtract(const Duration(days: 2)),
        favoriteCount: 23,
        commentCount: 4,
        favoritedUserIds: ['user_004'],
      ),
      PostModel(
        postId: 'post_007',
        userId: 'user_007',
        content:
            'Madagascar is full of surprises! Getting to interact with these amazing baboons feels like a dream. Their curiosity and closeness make this journey even more special. So lucky to have such a unique moment in this magical land. 🐒💫',
        mediaUrls: ['assets/images/p14.png'],
        videoThumbnails: [
          '', // 第一张是图片
        ],
        publishTime: DateTime.now().subtract(const Duration(days: 2, hours: 6)),
        favoriteCount: 156,
        commentCount: 23,
        favoritedUserIds: ['user_001', 'user_002', 'user_003', 'user_005'],
      ),
      PostModel(
        postId: 'post_008',
        userId: 'user_008',
        content:
            'Walking among the baobab trees in Madagascar is like stepping into a fairy tale. These ancient giants stand tall, creating a scene that’s both majestic and serene. So blessed to witness the beauty of this unique land. 🌳✨',
        mediaUrls: ['assets/images/p15.png'],
        videoThumbnails: [
          '', // 第一张是图片
        ],
        publishTime: DateTime.now().subtract(const Duration(days: 3)),
        favoriteCount: 41,
        commentCount: 7,
        favoritedUserIds: ['user_001', 'user_003'],
      ),
      PostModel(
        postId: 'post_009',
        userId: 'user_001',
        content:
            'Trekking through Madagascar\'s diverse landscapes is an absolute dream! From lush rainforests to stunning river valleys, every step feels like an adventure. So in love with the wild beauty here. 🎒🌿',
        mediaUrls: [
          'assets/images/p16.png',
          'assets/images/p17.png',
          'assets/images/p18.png',
        ],
        videoThumbnails: ['', '', ''],
        publishTime: DateTime.now().subtract(const Duration(days: 3)),
        favoriteCount: 41,
        commentCount: 7,
        favoritedUserIds: ['user_001', 'user_003'],
      ),
    ];

    // 初始化默认用户收藏动态数据
    _userFavoritePostsMap = {};

    // 根据PostModel中的favoritedUserIds来同步初始化_userFavoritePostsMap
    for (final post in _postList) {
      for (final userId in post.favoritedUserIds) {
        if (!_userFavoritePostsMap.containsKey(userId)) {
          _userFavoritePostsMap[userId] = [];
        }
        if (!_userFavoritePostsMap[userId]!.contains(post.postId)) {
          _userFavoritePostsMap[userId]!.add(post.postId);
        }
      }
    }

    // 初始化默认评论数据
    _commentList = [
      CommentModel(
        commentId: 'comment_001',
        postId: 'post_001',
        userId: 'user_002',
        content:
            'Amazing footage! Ring-tailed lemurs are such social creatures. Did you notice their scent marking behavior?',
        commentTime: DateTime.now().subtract(const Duration(hours: 1)),
      ),
      CommentModel(
        commentId: 'comment_002',
        postId: 'post_001',
        userId: 'user_003',
        content:
            'Their communication calls are so complex! Each group has its own unique vocal patterns.',
        commentTime: DateTime.now().subtract(const Duration(minutes: 45)),
      ),
      CommentModel(
        commentId: 'comment_003',
        postId: 'post_002',
        userId: 'user_001',
        content:
            'Amazing footage! Aye-ayes are such fascinating creatures. Did you notice their unique foraging technique?',
        commentTime: DateTime.now().subtract(const Duration(hours: 1)),
      ),
      CommentModel(
        commentId: 'comment_004',
        postId: 'post_002',
        userId: 'user_003',
        content:
            'Their elongated middle finger is perfectly adapted for extracting grubs from tree bark!',
        commentTime: DateTime.now().subtract(const Duration(minutes: 45)),
      ),
      CommentModel(
        commentId: 'comment_005',
        postId: 'post_003',
        userId: 'user_001',
        content:
            'Incredible color transformation! How long did the entire process take?',
        commentTime: DateTime.now().subtract(const Duration(hours: 6)),
      ),
      CommentModel(
        commentId: 'comment_006',
        postId: 'post_003',
        userId: 'user_005',
        content:
            'Panther chameleons are truly masters of disguise! Their color changes serve both communication and temperature regulation.',
        commentTime: DateTime.now().subtract(const Duration(hours: 7)),
      ),
      CommentModel(
        commentId: 'comment_007',
        postId: 'post_005',
        userId: 'user_001',
        content:
            'Baobab trees are truly magnificent! I\'ve heard they can store up to 120,000 liters of water in their trunks.',
        commentTime: DateTime.now().subtract(const Duration(days: 1, hours: 1)),
      ),
      CommentModel(
        commentId: 'comment_008',
        postId: 'post_005',
        userId: 'user_007',
        content:
            'These ancient trees are crucial for local ecosystems. We need to protect them from deforestation!',
        commentTime: DateTime.now().subtract(const Duration(days: 1, hours: 2)),
      ),
      CommentModel(
        commentId: 'comment_009',
        postId: 'post_007',
        userId: 'user_001',
        content:
            'Thank you for your conservation efforts! Every action counts in protecting Madagascar\'s unique biodiversity.',
        commentTime: DateTime.now().subtract(const Duration(days: 2, hours: 4)),
      ),
      CommentModel(
        commentId: 'comment_010',
        postId: 'post_007',
        userId: 'user_003',
        content:
            'How can we get more involved in local conservation projects? I\'d love to contribute!',
        commentTime: DateTime.now().subtract(const Duration(days: 2, hours: 5)),
      ),
      CommentModel(
        commentId: 'comment_011',
        postId: 'post_008',
        userId: 'user_001',
        content:
            'Incredible craftsmanship! How long does it take them to build these nests?',
        commentTime: DateTime.now().subtract(const Duration(hours: 6)),
      ),
      CommentModel(
        commentId: 'comment_012',
        postId: 'post_008',
        userId: 'user_002',
        content:
            'Madagascar weavers are truly master builders! Each nest is a work of art.',
        commentTime: DateTime.now().subtract(const Duration(hours: 7)),
      ),
    ];

    // 更新 Beacon 状态
    postListBeacon.value = List.from(_postList);
    commentListBeacon.value = List.from(_commentList);
    userFavoritePostsMapBeacon.value = Map.from(_userFavoritePostsMap);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultData();
  }

  /// 获取所有动态
  static List<PostModel> getAllPosts() {
    _initializeDefaultData();
    return _postList;
  }

  /// 根据用户ID获取动态
  static List<PostModel> getPostsByUserId(String userId) {
    _initializeDefaultData();
    return _postList.where((post) => post.userId == userId).toList();
  }

  /// 根据ID获取动态详情
  static PostModel? getPostById(String postId) {
    _initializeDefaultData();
    try {
      return _postList.firstWhere((post) => post.postId == postId);
    } catch (e) {
      return null;
    }
  }

  /// 发布新动态
  static void publishPost({
    required String userId,
    required String content,
    required List<String> mediaUrls,
    required List<String> videoThumbnails,
  }) {
    _initializeDefaultData();
    final newPost = PostModel(
      postId: 'post_${DateTime.now().millisecondsSinceEpoch}',
      userId: userId,
      content: content,
      mediaUrls: mediaUrls,
      videoThumbnails: videoThumbnails,
      publishTime: DateTime.now(),
      favoriteCount: 0,
      commentCount: 0,
      favoritedUserIds: [],
    );
    _postList.insert(0, newPost);
    postListBeacon.value = List.from(_postList);
  }

  /// 删除动态
  static bool removePost(String postId) {
    _initializeDefaultData();
    final postIndex = _postList.indexWhere((post) => post.postId == postId);
    if (postIndex == -1) return false;

    _postList.removeAt(postIndex);
    postListBeacon.value = List.from(_postList);
    return true;
  }

  /// 获取动态的评论列表
  static List<CommentModel> getPostComments(String postId) {
    _initializeDefaultData();
    return _commentList.where((comment) => comment.postId == postId).toList();
  }

  /// 添加评论
  static void addComment({
    required String postId,
    required String userId,
    required String content,
  }) {
    _initializeDefaultData();
    final newComment = CommentModel(
      commentId: 'comment_${DateTime.now().millisecondsSinceEpoch}',
      postId: postId,
      userId: userId,
      content: content,
      commentTime: DateTime.now(),
    );
    _commentList.add(newComment);
    commentListBeacon.value = List.from(_commentList);

    // 更新动态的评论数
    final postIndex = _postList.indexWhere((post) => post.postId == postId);
    if (postIndex != -1) {
      final post = _postList[postIndex];
      _postList[postIndex] = post.copyWith(commentCount: post.commentCount + 1);
      postListBeacon.value = List.from(_postList);
    }
  }

  /// 删除评论
  static bool removeComment(String postId, String commentId) {
    _initializeDefaultData();
    final commentIndex = _commentList.indexWhere(
      (comment) => comment.commentId == commentId,
    );
    if (commentIndex == -1) return false;

    _commentList.removeAt(commentIndex);
    commentListBeacon.value = List.from(_commentList);

    // 更新动态的评论数
    final postIndex = _postList.indexWhere((post) => post.postId == postId);
    if (postIndex != -1) {
      final post = _postList[postIndex];
      _postList[postIndex] = post.copyWith(commentCount: post.commentCount - 1);
      postListBeacon.value = List.from(_postList);
    }

    return true;
  }

  /// 切换动态收藏状态
  static bool togglePostFavorite(String userId, String postId) {
    _initializeDefaultData();
    final postIndex = _postList.indexWhere((post) => post.postId == postId);
    if (postIndex == -1) return false;

    final post = _postList[postIndex];
    final favoritedIndex = post.favoritedUserIds.indexOf(userId);

    if (favoritedIndex != -1) {
      // 已收藏，取消收藏
      final newFavoritedUserIds = List<String>.from(post.favoritedUserIds);
      newFavoritedUserIds.removeAt(favoritedIndex);
      _postList[postIndex] = post.copyWith(
        favoritedUserIds: newFavoritedUserIds,
        favoriteCount: post.favoriteCount - 1,
      );
      postListBeacon.value = List.from(_postList);

      // 更新用户收藏映射
      _updateUserFavoritePostsMap(userId, postId, false);
      return false;
    } else {
      // 未收藏，添加收藏
      final newFavoritedUserIds = List<String>.from(post.favoritedUserIds);
      newFavoritedUserIds.add(userId);
      _postList[postIndex] = post.copyWith(
        favoritedUserIds: newFavoritedUserIds,
        favoriteCount: post.favoriteCount + 1,
      );
      postListBeacon.value = List.from(_postList);

      // 更新用户收藏映射
      _updateUserFavoritePostsMap(userId, postId, true);
      return true;
    }
  }

  /// 更新用户收藏映射
  static void _updateUserFavoritePostsMap(
    String userId,
    String postId,
    bool isFavorited,
  ) {
    if (!_userFavoritePostsMap.containsKey(userId)) {
      _userFavoritePostsMap[userId] = [];
    }

    final userFavorites = List<String>.from(_userFavoritePostsMap[userId]!);

    if (isFavorited) {
      if (!userFavorites.contains(postId)) {
        userFavorites.add(postId);
      }
    } else {
      userFavorites.remove(postId);
    }

    _userFavoritePostsMap[userId] = userFavorites;
    userFavoritePostsMapBeacon.value = Map.from(_userFavoritePostsMap);
  }

  /// 检查用户是否已收藏动态
  static bool isPostFavorited(String userId, String postId) {
    _initializeDefaultData();
    final post = getPostById(postId);
    return post?.favoritedUserIds.contains(userId) ?? false;
  }

  /// 获取用户收藏的动态列表
  static List<PostModel> getUserFavoritePosts(String userId) {
    _initializeDefaultData();
    final userFavorites = _userFavoritePostsMap[userId] ?? [];
    return _postList
        .where((post) => userFavorites.contains(post.postId))
        .toList();
  }

  /// 根据用户ID获取用户信息（用于显示用户名和头像）
  static Map<String, String>? getUserInfo(String userId) {
    final user = UserState.queryUserById(userId);
    if (user != null) {
      return {'userName': user.userName, 'userAvatar': user.avatar};
    }
    return null;
  }

  /// 创建新动态
  static void createPost({
    required String postId,
    required String userId,
    required String content,
    required List<String> mediaUrls,
    required List<String> videoThumbnails,
  }) {
    _initializeDefaultData();

    final newPost = PostModel(
      postId: postId,
      userId: userId,
      content: content,
      mediaUrls: mediaUrls,
      videoThumbnails: videoThumbnails,
      publishTime: DateTime.now(),
      favoriteCount: 0,
      commentCount: 0,
      favoritedUserIds: [],
    );

    // 将新动态添加到列表开头
    _postList.insert(0, newPost);

    // 更新状态
    postListBeacon.value = List.from(_postList);
  }

  // Getters for reactive state
  static ReadableBeacon<List<PostModel>> get postList => postListBeacon;
  static ReadableBeacon<List<CommentModel>> get commentList =>
      commentListBeacon;
  static ReadableBeacon<Map<String, List<String>>> get userFavoritePostsMap =>
      userFavoritePostsMapBeacon;
}
